<?php
namespace app\common\component\user_wallet_dynamic;

use app\common\model\UserWalletDynamic;

use app\common\component\user\UserModel;

class UserWalletDynamicService {
	public function reward($user_id, $price) {
		$getUser = UserModel::get(['user_id' => $user_id]);

		if(!$getUser) {
			return ['code' => 0, 'message' => '用户不存在'];
		}

		if($getUser -> getData('promotion_id') == 0) {
			return ['code' => 0, 'message' => '没有推荐人'];
		}

		$currentTime = time();
		$overTime = $currentTime + getParam('DYNAMIC_REWARD_OVER_TIME') * 24 * 60 * 60;
		$layers = json_decode(getParam('USER_REWARD_LAYERS_JSON'), true);
		$layersPeople = json_decode(getParam('USER_REWARD_LAYERS_PEOPLE_JSON'), true);
		$resultPromotionUser = UserModel::get(['user_id' => $getUser -> getData('promotion_id')]);
		foreach($layers as $k => $reward) {
			if($reward == 0) {
				continue;
			}

			$promotionId = $resultPromotionUser -> getData('promotion_id');
			if($promotionId == 0) {
				return ['code' => 0, 'message' => '没有推荐人'];
			}

			$totalPromotion = UserModel::where('promotion_id', $resultPromotionUser -> getData('user_id')) -> count();
			if($totalPromotion >= $layersPeople[$k]) {
				$price = $price * $reward / 100;
				$this -> create([
					'user_id' => $resultPromotionUser -> getData('user_id'),
					'from_user_id' => $user_id,
					'type' => 1,
					'status' => 0,
					'price' => $price,
					'remaining_price' => $price,
					'create_time' => $currentTime,
					'over_time' => $overTime
				]);
			}

			$resultPromotionUser = UserModel::get(['user_id' => $promotionId]);
		}

		return ['code' => 0, 'message' => '奖金发放完成!'];
	}

	public function rewardOverTime() {
		$selectUserWalletDynamic = UserWalletDynamic::where('status = 0 AND over_time < ' . time()) -> select();
		if(empty($selectUserWalletDynamic)) {
			return false;
		}

		foreach($selectUserWalletDynamic as $userWalletDynamic) {
			$userWalletDynamic -> status = 8;

			$userWalletDynamic -> save();
		}
	}

	public function create($data) {
		$UserWalletDynamic = new UserWalletDynamic($data);

    	if($UserWalletDynamic -> save()) {
    		return [
    			'code' => 0,
    			'message' => '动态钱包创建成功!',
    			'data' => [
    				'user_wallet_dynamic' => $UserWalletDynamic
    			]
    		];
    	}

    	return [
			'code' => -1,
			'message' => '动态钱包创建失败!'
		];
	}
}
?>